/// 
/// Author: Jeff Liu
/// Date: 2023-04-18 10:09:36
/// LastEditTime: 2023-06-30 11:19:56
/// LastEditors: Jeff Liu
/// Description: 
/// FilePath: /CCH/src/cls/HCC/SVR/PubSub/Subscription.cls
/// Jeff.liu@intersytems.com
/// 
Class HCC.SVR.PubSub.Subscription Extends (%Persistent, %XML.Adaptor, %JSON.Adaptor) [ DdlAllowed ]
{

/// 订阅者  
Property Subscriber As HCC.SVR.PubSub.Subscriber [ Required ];

/// 订阅主题
Property Topic As Topic [ Required ];

/// Ture 为同步 False为异步
Property IsSync As %Boolean [ Required ];

/// 订阅是否生效
Property IsEnabled As %Boolean [ InitialExpression = 1, Required ];

/// 创建时间
Property CreatedAt As %TimeStamp [ InitialExpression = {$ZDATETIME($ZDATETIMEH($ZTS,-3),3,1,4)} ];

/// 创建时间索引
Index IndexCreatedAt On CreatedAt;

/// 联合主键 subscriber + TopicName
Index IndexSubscriberTopic On (Subscriber, Topic) [ Unique ];

/// 获得主题的订阅者
ClassMethod GetSubscribtionByTopic(topic As %String) As %ListOfDataTypes
{
    set tID =""
  &SQL(SELECT ID into :tID from HCC_SVR_PubSub.Topic where TopicName = :topic) 
  set subscriptionIDs=##class(%ListOfDataTypes).%New()
  set query = "SELECT a.ID FROM HCC_SVR_PubSub.Subscription a join HCC_SVR_PubSub.Subscriber b on a.Subscriber=b.ID  WHERE a.Topic = ? and a.IsEnabled = 1 and b.IsActive =1"
  set statement = ##class(%SQL.Statement).%New()
  set status = statement.%Prepare(query)
  set rset = statement.%Execute(tID)
  while rset.%Next()
  {
    do subscriptionIDs.Insert( rset.%Get("ID"))
  }
  for i = 1:1:subscriptionIDs.Count() {write !, subscriptionIDs.GetAt(i)}
  Return subscriptionIDs
}


}
